package cn.lger.controller;

import cn.lger.pojo.*;
import cn.lger.service.*;
import cn.lger.util.StringEmptyUtil;
import cn.lger.util.ValidateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Code that Changed the World
 *
 * @author Pro
 * @date 2018-06-17.
 */
@RestController
@RequestMapping("api/admin")
@Api(tags = "管理员控制器")
public class AdminController {

    @Resource
    private AdminService adminService;
    @Resource
    private ContactService contactService;
    @Resource
    private ArticleService articleService;
    @Resource
    private CommentService commentService;
    @Resource
    private CategoryService categoryService;

    @GetMapping("contact/list")
    @ApiOperation(httpMethod = "GET", value = "查询所有反馈")
    @ApiResponse(code = 200, message = "成功", response = Page.class)
    public Page<Contact> getContacts(@ApiParam("当前页，默认0") Integer currentPage,
                                     @ApiParam("一页大小，默认3") Integer size){
        return contactService.findOnePage(currentPage, size);
    }

    @GetMapping("comment/list")
    @ApiOperation(httpMethod = "GET", value = "查询所有评论")
    @ApiResponse(code = 200, message = "成功", response = Page.class)
    public Page<Comment> getComments(@ApiParam("当前页，默认0") Integer currentPage,
                                     @ApiParam("一页大小，默认3") Integer size){
        return commentService.findOnePage(currentPage, size);
    }

    @PostMapping("category")
    @ApiOperation(httpMethod = "POST", value = "增加分类")
    @ApiResponse(code = 200, message = "返回插入成功后的分类实体", response = Category.class)
    public Category postCategory(Category category){
        return categoryService.insertOne(category);
    }

    @GetMapping("category/list")
    @ApiOperation(httpMethod = "GET", value = "获取一页文章分类")
    @ApiResponse(code = 200, message = "成功", response = Page.class)
    public Page<Category> getOnePageCategory(@ApiParam("当前页，默认0") Integer currentPage,
                                             @ApiParam("一页大小，默认3") Integer size){
        return categoryService.findOnePage(currentPage, size);
    }

    @DeleteMapping("article/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "删除相应id的文章")
    public int deleteArticle(@ApiIgnore @PathVariable int id){
        return articleService.deleteOneById(id);
    }

    @DeleteMapping("comment/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "删除相应id的评论")
    public int deleteComment(@ApiIgnore @PathVariable int id){
        return commentService.deleteOneById(id);
    }

    @DeleteMapping("contact/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "删除相应id的联系反馈")
    public int deleteContact(@ApiIgnore @PathVariable int id){
        return contactService.deleteOneById(id);
    }

    @DeleteMapping("category/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "删除相应id的分类")
    public int deleteCategory(@ApiIgnore @PathVariable int id){
        return categoryService.deleteOneById(id);
    }

    @PutMapping
    @ApiOperation(value = "修改管理员自己的信息", httpMethod = "PUT")
    public Administrator putAdmin(@ApiParam("邮箱") String email,
                        @ApiParam("密码") String password,
                        @ApiIgnore HttpSession session) {
        Administrator sessionAdmin = getSessionAdmin(session);
        Administrator admin = new Administrator();
        admin.setUsername(sessionAdmin.getUsername());
        admin.setId(sessionAdmin.getId());
        admin.setPassword(password);

        if (StringEmptyUtil.notEmpty(email)) {
            if (ValidateUtil.isValidEmail(email)) {
                admin.setEmail(email);
            }else {
                throw new IllegalArgumentException("邮箱格式不正确");
            }
        }
        if (adminService.update(admin) != 0) {
            admin.setSuperadmin(sessionAdmin.getSuperadmin());
            session.setAttribute("admin", admin);
        }
        return admin;
    }

    @PostMapping
    @ApiOperation(value = "增加普通管理员", httpMethod = "POST")
    public Administrator postAdmin(@Validated @ApiParam("管理员实体") Administrator admin,
                                   @ApiIgnore HttpSession session,
                                   @ApiIgnore HttpServletResponse response) {
        Administrator sessionAdmin = getSessionAdmin(session);
        if (Administrator.SUPER.equals(sessionAdmin.getSuperadmin())){
            if (!ValidateUtil.isValidEmail(admin.getEmail())){
                throw new IllegalArgumentException("邮箱格式不对劲");
            }
            admin.setSuperadmin(Administrator.NORMAL);
            if (adminService.insertOne(admin) != 0){
                return admin;
            }else {
                return null;
            }
        } else {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            throw new IllegalStateException("管理员权限不够");
        }
    }

    @GetMapping("list")
    @ApiOperation(value = "获取全部管理员", httpMethod = "GET")
    public Page<Administrator> getAdmins(@ApiParam("当前页，默认0") Integer currentPage,
                                         @ApiParam("一页大小，默认3") Integer size,
                                         @ApiIgnore HttpSession session,
                                         @ApiIgnore HttpServletResponse response) {
        Administrator sessionAdmin = getSessionAdmin(session);
        if (Administrator.SUPER.equals(sessionAdmin.getSuperadmin())){
            return adminService.findOnePage(currentPage, size);
        } else {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            throw new IllegalStateException("管理员权限不够");
        }
    }

    @DeleteMapping("{id}")
    @ApiOperation(value = "删除普通管理员", httpMethod = "DELETE")
    public int getAdmins(@ApiIgnore @PathVariable int id,
                                         @ApiIgnore HttpSession session,
                                         @ApiIgnore HttpServletResponse response) {
        Administrator sessionAdmin = getSessionAdmin(session);
        if (Administrator.SUPER.equals(sessionAdmin.getSuperadmin())){
            if (sessionAdmin.getId() == id){
                return 0;
            }
            return adminService.deleteOneById(id);
        } else {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            throw new IllegalStateException("管理员权限不够");
        }
    }

    @GetMapping("check")
    @ApiOperation(value = "检查该用户名是否存在", httpMethod = "GET")
    public int checkUsername(@ApiParam(value = "用户名", required = true) @RequestParam String username) {
        return adminService.checkUsername(username);
    }

    private Administrator getSessionAdmin(HttpSession session) {
        Object o = session.getAttribute("admin");
        Administrator admin;
        if (o instanceof Administrator) {
            admin = (Administrator) o;
        } else {
            throw new IllegalStateException("用户未登录，请登录后访问");
        }
        return admin;
    }


}
